package repository

import (
	"dataaysn/internal/model"
	"time"

	"gorm.io/gorm"
)

type TaskLogRepository interface {
	CreateLog(log *model.TaskLog) error
	GetLog(id string) (*model.TaskLog, error)
	ListLogs(taskID string, startTime, endTime time.Time) ([]model.TaskLog, error)
	GetLatestLog(taskID string) (*model.TaskLog, error)
}
type gormTaskLogRepository struct {
	db *gorm.DB
}

func NewGormTaskLogRepository(db *gorm.DB) TaskLogRepository {
	return &gormTaskLogRepository{db: db}
}

func (r *gormTaskLogRepository) CreateLog(log *model.TaskLog) error {
	return r.db.Create(log).Error
}

func (r *gormTaskLogRepository) GetLog(id string) (*model.TaskLog, error) {
	var log model.TaskLog
	err := r.db.First(&log, id).Error
	return &log, err
}

func (r *gormTaskLogRepository) ListLogs(taskID string, startTime, endTime time.Time) ([]model.TaskLog, error) {
	var logs []model.TaskLog
	query := r.db.Where("task_id = ?", taskID)

	if !startTime.IsZero() {
		query = query.Where("start_time >= ?", startTime)
	}
	if !endTime.IsZero() {
		query = query.Where("end_time <= ?", endTime)
	}

	err := query.Order("start_time desc").Find(&logs).Error
	return logs, err
}

func (r *gormTaskLogRepository) GetLatestLog(taskID string) (*model.TaskLog, error) {
	var log model.TaskLog
	err := r.db.Where("task_id = ?", taskID).
		Order("start_time desc").
		First(&log).Error

	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	return &log, err
}
